package com.guos.rateLimit.guava;

import com.google.common.util.concurrent.RateLimiter;

/**
 * 每一行代码，都是改变世界的力量
 * https://blog.csdn.net/ITkampong/article/details/83895904
 *
 * @author 郭帅
 * @date 2023/2/5 17:23
 */
public class Test {

    // 平滑突发限流
    public static void testSmoothBursty() {
        RateLimiter r = RateLimiter.create(5);
        while (true) {
            System.out.println("get 1 tokens: " + r.acquire() + "s");
        }
        /**
         * acquire 返回是获取 permit 的等待时间。
         * output: 基本上都是0.2s执行一次，符合一秒发放5个令牌的设定。
         * get 1 tokens: 0.0s
         * get 1 tokens: 0.182014s
         * get 1 tokens: 0.188464s
         * get 1 tokens: 0.198072s
         * get 1 tokens: 0.196048s
         * get 1 tokens: 0.197538s
         * get 1 tokens: 0.196049s
         */
    }

    public static void testSmoothBursty2() {
        RateLimiter r = RateLimiter.create(2);
        while (true) {
            System.out.println("get 1 tokens: " + r.acquire(10) + "s");
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
            }
//            System.out.println("get 1 tokens: " + r.acquire(1) + "s");
//            System.out.println("get 1 tokens: " + r.acquire(1) + "s");
//            System.out.println("get 1 tokens: " + r.acquire(1) + "s");
            System.out.println("end");
            /**
             * output:
             * get 1 tokens: 0.0s
             * get 1 tokens: 0.0s
             * get 1 tokens: 0.0s
             * get 1 tokens: 0.0s
             * end
             * get 1 tokens: 0.499796s
             * get 1 tokens: 0.0s
             * get 1 tokens: 0.0s
             * get 1 tokens: 0.0s
             */
        }
    }

    public static void testSmoothBursty3() {
        RateLimiter r = RateLimiter.create(5);
//        try {
//            TimeUnit.SECONDS.sleep(2);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        while (true) {
            System.out.println("get 7 tokens: " + r.acquire(7) + "s");
            System.out.println("get 1 tokens: " + r.acquire(1) + "s");
            System.out.println("get 1 tokens: " + r.acquire(1) + "s");
            System.out.println("get 1 tokens: " + r.acquire(1) + "s");
            System.out.println("end");
            /**
             * output:
             * get 7 tokens: 0.0s
             * get 1 tokens: 1.397538s
             * get 1 tokens: 0.192223s
             * get 1 tokens: 0.199256s
             * end
             * get 7 tokens: 0.195012s
             * get 1 tokens: 1.398722s
             * get 1 tokens: 0.19341s
             * get 1 tokens: 0.194322s
             * end
             */
        }
    }

    public static void main(String[] args) {
//        testSmoothBursty();
        testSmoothBursty2();
//        testSmoothBursty3();
    }
}
